import 'dart:async';
import 'dart:convert';

import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hi_cache/flutter_hi_cache.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/svg.dart';

import 'package:hktk_app/config/storage_key.dart';
import 'package:hktk_app/dao/download_dao.dart';
import 'package:hktk_app/dao/home_dao.dart';
import 'package:hktk_app/dao/industry_dao.dart';
import 'package:hktk_app/dao/live_dao.dart';
import 'package:hktk_app/dao/study_dao.dart';
import 'package:hktk_app/ienum/home/column_position_enum.dart';
import 'package:hktk_app/model/data_model.dart';
import 'package:hktk_app/model/home/column_model.dart';
import 'package:hktk_app/model/home/exam_key_model.dart';
import 'package:hktk_app/model/home/latest_model.dart';
import 'package:hktk_app/model/industry/category_model.dart';
import 'package:hktk_app/model/industry/exam_model.dart';
import 'package:hktk_app/model/live/live_model.dart';
import 'package:hktk_app/model/study/hot_material.dart';
import 'package:hktk_app/model/study/hot_share.dart';
import 'package:hktk_app/pages/tab/study.dart';

import 'package:hktk_app/util/dao_util.dart';
import 'package:hktk_app/util/data_util.dart';
import 'package:hktk_app/util/font_util.dart';
import 'package:hktk_app/util/my_util.dart';
import 'package:hktk_app/util/screen_adapter_helper.dart';
import 'package:hktk_app/util/toast_util.dart';
import 'package:hktk_app/util/view_util.dart';

import 'package:intl/intl.dart';

import 'package:hktk_app/common/widget/category_widget.dart';
import 'package:hktk_app/widget/home/home_title_widget.dart';
import 'package:hktk_app/pages/package/package_list.dart';
import 'package:hktk_app/pages/study/hot_share_html.dart';

// 180.h  36.h  56.h  33.h 195.h  33.h
// 230 +36.h +73+42+260+42   listView高度  底部栏
class MyHomePage extends StatefulWidget {
  final PageController parentController;
  final Function(int,int)? changeIndex;
  final void Function() changeState;
  final GlobalKey<StudyPageState> studyKey;
  const MyHomePage({super.key, required this.parentController, this.changeIndex, required this.changeState, required this.studyKey});

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage>
    with WidgetsBindingObserver, AutomaticKeepAliveClientMixin {
  // 热点分享
  late Future<dynamic> list;
  late bool showShare = false;
  late Future<int> _getCountDownFuture;

  late EasyRefreshController _controller;

  // 热门资料
  late Future<dynamic> list2;

  // 切换科目的controller
  final StreamController<List> _categoryController = StreamController();
  late List<CategoryModel> _categoryList;
  late int _categoryIndex;
  final List<Map<String, dynamic>> _list1 = [
    {
      // 直接跳转学习选课程页面，有免费就免费
      "text": '选课试听',
      "img": 'images/home/link_item1.svg',
      // "pageName": '/video-list',
      "onClick": (context) {
        Navigator.pushNamed(context, '/video-list');
      }
    },
    // {
    //   "text": '教材教辅',
    //   "img": 'images/home/link_item2.svg',
    //   "pageName": '/package-list',
    // },
    // {
    //   "text": '免费试看',
    //   "img": 'images/home/link_item3.svg',
    //   "pageName": "/free",
    // },
    {
      // 跳转到学习的资料页面
      "text": '笔记资料',
      "img": 'images/home/link_item4.svg',
      // "pageName": '/my-note',
      "onClick": (context) {
        Navigator.pushNamed(context, '/my-note');
      }
    },
    {
      // 跳转到学习的直播页面
      "text": '直播课程',
      "img": 'images/home/link_item5.svg',
      // "pageName": '/tab',
      // "arguments": {"pageIndex": 1, "subIndex": 1},
      "onClick": (BuildContext context) {
        // 不销毁的情况下跳转
        (context.widget as MyHomePage).changeIndex!(1,1);

        (context.widget as MyHomePage).parentController.jumpToPage(1);
        Future.delayed(Duration(milliseconds: 500),(){
          if(context.mounted){
            (context.widget as MyHomePage).studyKey.currentState!.tabController.animateTo(1);
            (context.widget as MyHomePage).changeState();
          }
        });
      }
    }
  ];

  // double topBackgroundHeight = 230.h;//   18/23
  double topBackgroundHeight = 180.h;
  String imgUrl =
      "http://yun-cdn.caishi.cn/cdn/huikao/png/202501/20250121113953420@广告.png";

  // @override
  // void didChangeAppLifecycleState(AppLifecycleState state) {
  //   super.didChangeAppLifecycleState(state);
  //   if (state == AppLifecycleState.resumed) {
  //     debugPrint("MyHomePage -> AppLifecycleState.resumed");
  //     // 应用程序从后台切换到前台
  //   } else if (state == AppLifecycleState.paused) {
  //     debugPrint("MyHomePage -> AppLifecycleState.paused");
  //
  //     // 应用程序进入后台
  //   } else if (state == AppLifecycleState.detached) {
  //     debugPrint("MyHomePage -> AppLifecycleState.detached");
  //     // 应用程序被分离（例如，用户切换到其他应用）
  //   } else if (state == AppLifecycleState.inactive) {
  //     debugPrint("MyHomePage -> AppLifecycleState.inactive");
  //     // 应用程序处于非活动状态（例如，用户收到通知）
  //   }
  // }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return EasyRefresh(
        controller: _controller,
        header: _myFreshHeader(),
        // footer: const ClassicFooter(showText:false),
        footer: NotLoadFooter(),
        onRefresh: () async {
          getInitData();
          // 刷新数据
          _controller.finishRefresh();
          _controller.resetFooter();
        },
        onLoad: () async {
          _controller.finishLoad(IndicatorResult.success);
        },
        child: Container(
            child: Stack(
          children: [
            ..._background(),
            SafeArea(
                child: Container(
                    width: ScreenUtil().screenWidth,
                    height: 1.sh -
                        (ScreenHelper.bottomNavigationBarHeight ?? 58) -
                        ScreenUtil().statusBarHeight,
                    // decoration: BoxDecoration(color: Color(0xFFFFFFFF)),
                    child: ListView(
                        physics: const AlwaysScrollableScrollPhysics(),
                        // crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          SizedBox(
                            height: 40,
                            child: _createCountDownFutureBuilder(),
                          ),
                          SizedBox(
                            height: 180.h - 40,
                          ),
                          // Padding(
                          //   padding: EdgeInsets.only(left: 10),
                          //   child: CateGoryWidget(
                          //     controller: _categoryController,
                          //     categoryList: _categoryList,
                          //     selectedIndex: _categoryIndex,
                          //   ),
                          // ),
                          Container(
                            height: 56.h,
                            width: ScreenUtil().screenWidth,
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                              children: <Widget>[
                                for (int i = 0; i < _list1.length; i++)
                                  InkWell(
                                      onTap: () {
                                        (_list1[i]["onClick"] as Function)(context);
                                      },
                                      child: Container(
                                          width: 100.w,
                                          child: Column(children: [
                                            SvgPicture.asset(
                                              _list1[i]["img"],
                                              width: 36.h,
                                              height: 36.h,
                                              // color: color,
                                              // color: Colors.red,
                                            ),
                                            Text(_list1[i]["text"])
                                          ]))),
                              ],
                            ),
                          ),
                          Container(
                              padding:
                                  EdgeInsets.only(top: 14, left: 16, bottom: 4),
                              child: Row(
                                mainAxisSize: MainAxisSize.min,
                                mainAxisAlignment: MainAxisAlignment.start,
                                crossAxisAlignment: CrossAxisAlignment.center,
                                children: [
                                  Text(
                                    '直播',
                                    style: TextStyle(
                                      color: Color(0xFF21242D),
                                      fontSize: 18,
                                      fontFamily: 'PingFang SC',
                                      fontWeight: FontWeight.w500,
                                      letterSpacing: 0.36,
                                    ),
                                  ),
                                ],
                              )),
                          TeacherCards(),
                          if (showShare)
                            Container(
                                padding: EdgeInsets.only(
                                    top: 14, left: 16, bottom: 4),
                                child: Row(
                                  mainAxisSize: MainAxisSize.min,
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  crossAxisAlignment: CrossAxisAlignment.center,
                                  children: [
                                    Text(
                                      '热门咨讯',
                                      style: TextStyle(
                                        color: Color(0xFF21242D),
                                        fontSize: 18,
                                        fontWeight: FontWeight.w500,
                                        letterSpacing: 0.36,
                                      ),
                                    ),
                                  ],
                                )),
                          _createHotShareFutureBuilder(),
                          Container(
                              padding:
                                  EdgeInsets.only(top: 14, left: 16, bottom: 4),
                              child: Row(
                                mainAxisSize: MainAxisSize.min,
                                mainAxisAlignment: MainAxisAlignment.start,
                                crossAxisAlignment: CrossAxisAlignment.center,
                                children: [
                                  Text(
                                    '热门资料',
                                    style: TextStyle(
                                      color: Color(0xFF21242D),
                                      fontSize: 18,
                                      fontFamily: 'PingFang SC',
                                      fontWeight: FontWeight.w500,
                                      letterSpacing: 0.36,
                                    ),
                                  ),
                                ],
                              )),
                          _createMaterialInfoFutureBuilder()
                        ])))
          ],
        )));
  }

  FutureBuilder _createMaterialInfoFutureBuilder() {
    DateFormat formatter = DateFormat('yyyy-MM-dd');
    return FutureBuilder(
      future: list2,
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          if (snapshot.data == null) return Container();
          List<dynamic> list = snapshot.data["records"] as List;
          List<Widget> widgetList = list.map((e) {
            return Column(children: [
              Container(
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.all(10),
                child: Text(
                  e['title']!,
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
              Container(
                padding: EdgeInsets.only(left: 10, bottom: 10, right: 10),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Container(
                      width: 220,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          Container(
                            width: 34,
                            height: 20,
                            alignment: Alignment.center,
                            // padding: const EdgeInsets.all(10),
                            decoration: ShapeDecoration(
                              shape: RoundedRectangleBorder(
                                side: BorderSide(
                                    width: 0.50, color: Color(0xFFF64E3A)),
                                borderRadius: BorderRadius.circular(2),
                              ),
                            ),
                            child: Text(
                              '推荐',
                              style: TextStyle(
                                color: Color(0xFFF64E3A),
                                fontSize: 14,
                                fontWeight: FontWeight.w400,
                              ),
                            ),
                          ),
                          Text(
                            '${e['watchTime'] ?? 0}人次浏览',
                            style: TextStyle(
                              color: Color(0xFFB2B2B2),
                              fontSize: 12,
                              fontWeight: FontWeight.w400,
                              letterSpacing: 0.12,
                            ),
                          ),
                        ],
                      ),
                    ),
                    Row(
                      spacing: 8,
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        // if (e['freeFlag'] != null && e['freeFlag'])
                        // if (e['freeFlag'] == null || !e['freeFlag'])
                        Row(spacing: 8, children: [
                          GestureDetector(
                            onTap: () {
                              // DateFormat
                              // Navigator.push
                              String url =
                                  coverHead + e["attachmentInfos"][0]["path"];

                              ExamKeyModel examKeyModel =
                                  IndustryDao.getExamKey();
                              DataModel dataModel = DataModel(
                                industryId: examKeyModel.industryId,
                                industryName: examKeyModel.industryName,
                                examId: examKeyModel.examId,
                                examName: examKeyModel.examName,
                                categoryId: 0,
                                categoryName: '',
                                myList: [],
                                visitorsType:
                                    dataUtilComm.dataModel.visitorsType,
                              );
                              List<String> nameAndType =
                                  e["attachmentInfos"][0]["name"].split(".");

                              DownloadDao.downloadFileWithExamId(
                                      url: url,
                                      dataModel: dataModel,
                                      name: nameAndType[0],
                                      type: nameAndType[1])
                                  .then((onValue) => {
                                        ToastUtil.show(
                                            context: context, msg: "下载成功")
                                      })
                                  .catchError((onError) => {
                                        ToastUtil.show(
                                            context: context, msg: "下载失败")
                                      });
                            },
                            child: Text(
                              "下载",
                              style: FontUtil.fontBlue1(14),
                            ),
                          ),
                          GestureDetector(
                              onTap: () {
                                // Navigator.push
                                if (e["attachmentInfos"] != null &&
                                    (e["attachmentInfos"] as List).isNotEmpty) {
                                  List<String> nameAndType =
                                      (e["attachmentInfos"][0]["name"]
                                              as String)
                                          .split(".");
                                  Navigator.pushNamed(context, "/preview-pdf",
                                      arguments: {
                                        "url": coverHead +
                                            e["attachmentInfos"][0]["path"],
                                        "name": nameAndType[0],
                                        "type": nameAndType[1],
                                        "netWork": true
                                      });
                                }
                              },
                              child: Text("查看", style: FontUtil.fontBlue1(14)))
                        ])
                      ],
                    )
                  ],
                ),
              ),
            ]);
          }).toList();
          return Padding(
            padding: EdgeInsets.only(left: 10, right: 10),
            child: Container(
                padding: EdgeInsets.only(top: 5, bottom: 5),
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(10)),
                child: Column(
                  children: widgetList,
                )),
          );
        } else
          return Container();
      },
    );
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    _controller = EasyRefreshController(
      controlFinishRefresh: true,
      controlFinishLoad: true,
    );
    // 获取直播列表
    _getCountDownFuture = () async {
      var lastModel = HiCache.getInstance().get(StorageKey.latestModel);
      ExamKeyModel examKey = IndustryDao.getExamKey();
      if (lastModel != null) {
        // 缓存1小时有效
        int lastRequestTime =
            HiCache.getInstance().get(StorageKey.homeRequestTime);
        if (lastRequestTime - DateTime.now().millisecondsSinceEpoch <
            1 * 60 * 60 * 1000) {
          Map<String, dynamic> jsonMap = json.decode(lastModel);
          if (jsonMap["examId"] == examKey.examId) {
            var examDate = json.decode(lastModel)['examDate'];
            String time = "${examDate!} 00:00:00";
            if (!MyUtil.getExpire(time)) {
              return 0;
            } else {
              return MyUtil.getSurplusDay(time);
            }
          }
          ;
        }
      }
      // 获取倒计时

      LatestModel model = await HomeDao.latestDate(examKey.examId);
      HiCache.getInstance()
          .setString(StorageKey.latestModel, json.encode(model.toJson()));
      HiCache.getInstance().setInt(
          StorageKey.homeRequestTime, DateTime.now().millisecondsSinceEpoch);
      if (model.examDate == null) {
        return 0;
      }
      String time = "${model.examDate!} 00:00:00";
      if (!MyUtil.getExpire(time)) {
        return 0;
      } else {
        return MyUtil.getSurplusDay(time);
      }
    }();

    getInitData();

    ExamKeyModel examKey = IndustryDao.getExamKey();
    // 存储相关id
    dataUtilComm.dataModel.industryId = examKey.industryId;
    dataUtilComm.dataModel.industryName = examKey.industryName;
    dataUtilComm.dataModel.examId = examKey.examId;
    dataUtilComm.dataModel.examName = examKey.examName;
    dataUtilComm.dataModel.categoryId =
        IndustryDao.getCategoryModels()[IndustryDao.getSelectCategoryId()!].id!;
    dataUtilComm.dataModel.categoryName =
        IndustryDao.getCategoryModels()[IndustryDao.getSelectCategoryId()!]
            .name!;

    // getCategoryModelsSel
    // _categoryList = IndustryDao.getCategoryModelsSel();
    // _categoryIndex = IndustryDao.getSelectCategoryId() ?? 0;
    // HomeDao.columnByCategory(categoryId:_categoryList[_categoryList.length-1].id!,groupId:getGroupId(),columnEnum:ColumnPositionEnum.jgqy);
    // LiveDao.getLiveList(columnId: '1888401672578220032',categoryId:_categoryList[_categoryList.length-1].id! );

    // _categoryController.stream.listen((_list) {
    //   //   切换科目
    //   int i = _list[0] as int;
    //   IndustryDao.saveSelectCategoryId(i);
    //   setState(() {
    //     _categoryIndex = i;
    //   });
    // });
  }

  void getInitData() async {
    ExamKeyModel examKey = IndustryDao.getExamKey();
    // list = StudyDao.getHotIndex(type: 0, examId: examKey.examId);
    // list2 = StudyDao.getHotIndex(type: 1, examId: examKey.examId);
    list = StudyDao.getHotIndex(type: 0, categoryId: dataUtilComm.dataModel.categoryId);
    list2 = StudyDao.getHotIndex(type: 1,categoryId: dataUtilComm.dataModel.categoryId);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();

    // 响应依赖变化
  }

  @override
  void didUpdateWidget(covariant MyHomePage oldWidget) {
    super.didUpdateWidget(oldWidget);
    // 响应 widget 配置变化
  }

  // @override
  // void deactivate() {
  //   super.deactivate();
  //   debugPrint("MyStatefulWidget -> deactivate");
  //   // 清理操作
  // }

  @override
  void dispose() {
    super.dispose();
    // debugPrint("MyStatefulWidget -> dispose");
    // 释放资源
    WidgetsBinding.instance.removeObserver(this);
    _categoryController.close();
    _controller.dispose();
  }

  List<Widget> _background() {
    var imageMargin = 10.0;
    return [
      // 顶部大背景
      Positioned(
        top: 0,
        left: 0,
        child: Image.asset(
          "images/home/background1.png",
          width: ScreenUtil().screenWidth,
          height: topBackgroundHeight,
          fit: BoxFit.fill,
        ),
      ),

      Positioned(
          top: 100.h,
          left: imageMargin,
          child: GestureDetector(
            onTap: () {
              // _onTapFun(banner);
            },
            child: ClipRRect(
              borderRadius: BorderRadius.circular(16),
              child: Image.network(
                imgUrl,
                // height: 150.h,
                width: ScreenUtil().screenWidth - 2 * imageMargin,
                fit: BoxFit.fill,
              ),
            ),
          )),
      Positioned(
        top: topBackgroundHeight,
        child: Container(
          height: 1.0.sh - topBackgroundHeight,
          decoration: BoxDecoration(
            color: Color(0xFFF5F5F5),
          ),
        ),
      )
    ];
  }

  FutureBuilder _createHotShareFutureBuilder() {
    DateFormat formatter = DateFormat('yyyy-MM-dd');
    return FutureBuilder(
      future: list,
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          if (snapshot.data == null) {
            showShare = false;
            return Container();
          }
          List<dynamic> list = snapshot.data!["records"];
          if (list.isNotEmpty) {
            showShare = true;
          }

          List<Widget> widgetList = list.map((e) {
            // MaterialInfoModel e1 = MaterialInfoModel.fromJson(e);
            return Column(children: [
              Container(
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.all(10),
                child: Text(
                  e['title']!,
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
              Container(
                padding: EdgeInsets.only(left: 10, right: 10),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  spacing: 5,
                  children: [
                    Container(
                      width: 220,
                      child: Row(
                        children: [
                          Container(
                            width: 34,
                            height: 20,
                            alignment: Alignment.center,
                            // padding: const EdgeInsets.all(10),
                            decoration: ShapeDecoration(
                              shape: RoundedRectangleBorder(
                                side: BorderSide(
                                    width: 0.50, color: Color(0xFFF64E3A)),
                                borderRadius: BorderRadius.circular(2),
                              ),
                            ),
                            child: Text(
                              '推荐',
                              style: TextStyle(
                                color: Color(0xFFF64E3A),
                                fontSize: 14,
                                fontFamily: 'Microsoft YaHei UI',
                                fontWeight: FontWeight.w400,
                              ),
                            ),
                          ),
                          Text(
                            '${e['watchTime'] ?? 0}人次浏览',
                            style: TextStyle(
                              color: Color(0xFFB2B2B2),
                              fontSize: 12,
                              fontFamily: 'PingFang SC',
                              fontWeight: FontWeight.w400,
                              letterSpacing: 0.12,
                            ),
                          ),
                        ],
                      ),
                    ),
                    if (e['releasedTime'] != null)
                      Text(
                        formatter.format(DateTime.parse(e['releasedTime']!)),
                        // formatter.format(DateTime(2022, 11, 11)),
                        style: TextStyle(
                          color: Color(0xFFB2B2B2),
                          fontSize: 12,
                          fontFamily: 'PingFang SC',
                          fontWeight: FontWeight.w400,
                          letterSpacing: 0.12,
                        ),
                      ),
                    // 下载、预览按钮
                    Row(spacing: 8, children: [
                      GestureDetector(
                        onTap: () {
                          // DateFormat
                          // Navigator.push
                          String url =
                              coverHead + e["attachmentInfos"][0]["path"];
                          ExamKeyModel examKeyModel = IndustryDao.getExamKey();
                          DataModel dataModel = DataModel(
                            industryId: examKeyModel.industryId,
                            industryName: examKeyModel.industryName,
                            examId: examKeyModel.examId,
                            examName: examKeyModel.examName,
                            categoryId: 0,
                            categoryName: '',
                            myList: [],
                            visitorsType: dataUtilComm.dataModel.visitorsType,
                          );
                          List<String> nameAndType =
                              e["attachmentInfos"][0]["name"].split(".");

                          DownloadDao.downloadFileWithExamId(
                              url: url,
                              dataModel: dataModel,
                              name: nameAndType[0],
                              type: nameAndType[1]);
                        },
                        child: Text(
                          "下载",
                          style: FontUtil.fontBlue1(14),
                        ),
                      ),
                      GestureDetector(
                          onTap: () {
                            // Navigator.push
                            if (e["attachmentInfos"] != null &&
                                (e["attachmentInfos"] as List).isNotEmpty) {
                              List<String> nameAndType =
                                  (e["attachmentInfos"][0]["name"] as String)
                                      .split(".");
                              Navigator.pushNamed(context, "/preview-pdf",
                                  arguments: {
                                    "url": coverHead +
                                        e["attachmentInfos"][0]["path"],
                                    "name": nameAndType[0],
                                    "type": nameAndType[1],
                                    "netWork": true
                                  });
                            }
                          },
                          child: Text("查看", style: FontUtil.fontBlue1(14)))
                    ])
                  ],
                ),
              )
            ]);
          }).toList();
          return Padding(
            padding: EdgeInsets.only(left: 10, right: 10),
            child: Container(
                padding: EdgeInsets.only(top: 5, bottom: 5),
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(10)),
                child: Column(
                  children: widgetList,
                )),
          );
          ;
        } else {
          return Center(
            child: Text(""),
          );
        }
      },
    );
  }

  FutureBuilder _createCountDownFutureBuilder() {
    return FutureBuilder(
        future: _getCountDownFuture,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            var countdown = snapshot.data!;
            return HomeTitleWidget(
                countdown: countdown,
                categoryName: IndustryDao.getExamKey().examName);
          } else {
            return Container();
          }
        });
  }

  @override
  //   wantKeepAlive
  bool get wantKeepAlive => true;

  _myFreshHeader() {
    return ClassicHeader(
      dragText: "下拉开始刷新",
      armedText: "松开后开始刷新",
      readyText: "正在刷新...",
      processingText: "正在刷新...",
      processedText: "刷新完成",
      messageBuilder: (
        BuildContext context,
        IndicatorState state,
        String text,
        DateTime dateTime,
      ) {
        String hour = getDateStr(dateTime.hour);
        String minute = getDateStr(dateTime.minute);
        return Text(
          "上次刷新时间：$hour:$minute",
          // style: FontUtil.fontBlue1(20),
        );
      },
      pullIconBuilder: (
        BuildContext context,
        IndicatorState state,
        double animation,
      ) {
        // debugPrint("state ===> ${state.mode}");
        if (state.mode == IndicatorMode.drag) {
          // 下拉开始刷新
          return _getIcon(Icons.arrow_downward);
        } else if (state.mode == IndicatorMode.armed) {
          // 松开后开始刷新
          return _getIcon(Icons.arrow_upward);
        } else if (state.mode == IndicatorMode.ready ||
            state.mode == IndicatorMode.processing) {
          // 正在刷新...
          return SizedBox(
            width: 30,
            height: 30,
            child: CircularProgressIndicator(
              color: colorBlue1,
              strokeWidth: 4,
            ),
          );
        } else if (state.mode == IndicatorMode.processed) {
          // 刷新完成
          return _getIcon(Icons.check);
        }
        return Container();
      },
    );
  }

  Widget _getIcon(IconData iconData) {
    return Icon(
      iconData,
      size: 35,
      color: colorBlue1,
    );
  }
}

class TeacherCards extends StatefulWidget {
  const TeacherCards({
    super.key,
  });

  @override
  State<StatefulWidget> createState() => _createTeacherState();
}

class _createTeacherState extends State<TeacherCards> {
  late Future<dynamic> _future;

  @override
  void initState() {
    super.initState();
    // _future = HomeDao.getTeacherList();
    _future = LiveDao.getVideoList();
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
        future: _future,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            var data = snapshot.data["records"];
            if (data.length > 0) {
              return SingleChildScrollView(
                padding: EdgeInsets.only(left: 10, right: 10),
                scrollDirection: Axis.horizontal, // 水平滚动
                child: Row(
                  children: [
                    for (int i = 0; i < data.length; i++)
                      _createCard(LiveModel.fromJson(data[i]))
                  ],
                ),
              );
            } else {
              return Container(
                height: 195.h,
                margin: EdgeInsets.only(left: 10, right: 10),
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(5)),
                child: Center(
                  child: SvgPicture.asset("images/home/empty.svg", width: 150),
                ),
              );
            }
          } else {
            return Container();
          }
        });
  }

  Widget _createCard(LiveModel liveModel) {
    double cardWidth = 195;
    double cardHeight = 195.h;
    return Container(
      width: cardWidth,
      height: cardHeight,
      margin: EdgeInsets.only(right: 5),
      decoration: ShapeDecoration(
        image: DecorationImage(
          image: AssetImage("images/home/teacher_background.png"),
          fit: BoxFit.fill,
        ),
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(4)),
      ),
      child: Stack(alignment: Alignment.center, children: [
        // teacherImg
        Image.asset("images/test/1.png"),
        Positioned(
          top: cardHeight - 86,
          child: Container(
            width: cardWidth,
            height: 86,
            decoration: ShapeDecoration(
              color: Color(0xFFF3FAFF),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.only(
                  bottomLeft: Radius.circular(4),
                  bottomRight: Radius.circular(4),
                ),
              ),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SizedBox(
                  // width: 152,
                  child: Text.rich(
                    TextSpan(
                      children: [
                        TextSpan(
                          text: '免费',
                          style: TextStyle(
                            color: Color(0xFF6CC683),
                            fontSize: 14,
                            fontFamily: 'PingFang SC',
                            fontWeight: FontWeight.w400,
                            height: 1,
                            letterSpacing: 0.28,
                          ),
                        ),
                        TextSpan(
                          text: liveModel.title,
                          style: TextStyle(
                            color: Color(0xFF21242D),
                            fontSize: 14,
                            fontFamily: 'PingFang SC',
                            fontWeight: FontWeight.w400,
                            height: 1,
                            letterSpacing: 0.28,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
                Text(
                  "${liveModel.liveDate!} ${liveModel.startTime}-${liveModel.endTime}",
                  style: TextStyle(
                    fontSize: 12,
                    color: Color(0xFF5C5C5C),
                  ),
                ),
                Container(
                  width: cardWidth,
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Text(
                        '${liveModel.appointmentNum}人预约',
                        style: TextStyle(
                          color: Color(0xFF5C5C5C),
                          fontSize: 11,
                          fontFamily: 'Microsoft YaHei UI',
                          fontWeight: FontWeight.w400,
                        ),
                      ),
                      // 已结束的不可预约
                      GestureDetector(
                        onTap: () async {
                          //   查看是否已经预约
                          dynamic res =
                              await LiveDao.haveAppoint(liveId: liveModel.id!);
                          if (res == true) {
                            ToastUtil.show(
                                context: context, msg: "您已经预约,无需重复预约");
                            return;
                          } else {
                            dynamic res1 = await LiveDao.appoint(liveModel.id!);
                            if (res1 == true) {
                              ToastUtil.show(context: context, msg: "预约成功");
                            } else {
                              ToastUtil.show(context: context, msg: "预约失败");
                            }
                          }
                        },
                        child: Container(
                          width: 54,
                          height: 22,
                          padding: const EdgeInsets.symmetric(
                              horizontal: 10, vertical: 2),
                          decoration: ShapeDecoration(
                            color: Color(0xFF3C6CFF),
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(90),
                            ),
                          ),
                          alignment: Alignment.center,
                          child: Text(
                            '预约',
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 12,
                              fontWeight: FontWeight.w400,
                              letterSpacing: 0.12,
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        )
      ]),
    );
  }
}
